<?php       exit;
include_once('include/ini.php');

       function ArrFromQuery($query)
     {
	      global $db;
        $arr = array();
          $result = $db->sql_query($query);
          if (!$result)
            return false;
          $i = 0;
          while ( $row = $db->sql_fetchrow($result) )
          {
              foreach ( $row as $key => $value )
              {
                 $arr[$i][$key] = $value;
              }
              $i++;
          }
 		  mysql_free_result($result); 
          return $arr;
      }


	// hash + hash 2010
	function selectHash($hashTable, $id=1329)
	{
    $query = "select * from $hashTable where id > $id and used = 1";
		// run query
		$hashsArray = ArrFromQuery($query);//result
		return $hashsArray;
	}
	
	function calculateItems($hashsArray, $foundItemsTable, $foundItemsResultTable)
	{       global $db;
		$items = array();
		foreach ($hashsArray as $row=>$value)
		{
			if (!isset($items[$value['user_id']][$value['item_id']]))
			{
				$items[$value['user_id']][$value['item_id']] = 0;
				// set null to all ??
				$query = "select * from $foundItemsResultTable where user_id=".$value['user_id']." and item_id=".$value['item_id'];
		//		echo $query."<br>";
				$result = ArrFromQuery($query);
				// run query
				if (!$result || empty($result))
				{ 
					$query = "insert into $foundItemsResultTable set user_id=".$value['user_id'].", item_id=".$value['item_id'].", count=0";    
					// run query
					$result = $db->sql_query($query);
				}
				else echo 'no';
			}
			
			$items[$value['user_id']][$value['item_id']]++;
		}
		return $items;
	}

	function saveItemsCount($items, $foundItemsTable)
	{       global $db;
		foreach ($items as $row=>$value)
		{
			foreach ($value as $row1=>$value1)
			{
				$query = "update $foundItemsTable set count=count+$value1 where user_id=$row and item_id=$row1";         
        $result = $db->sql_query($query);
				// $query = "update $foundItemsTable set count=count+$value1 where user_id=$row and item_id=$row1";
				// run query
			}
		}
	}
	
	$hashsArray = selectHash('hashs', 0);
	$hashsArray2010 = selectHash('hashs_2010');
	
	$items = calculateItems($hashsArray, 'found_items', 'found_items_bak');
	$items2010 = calculateItems($hashsArray2010, 'found_items_2010', 'found_items_bak');
	
	saveItemsCount($items, 'found_items_bak');
	saveItemsCount($items2010, 'found_items_bak');

?>
